package com.dataseek.iot.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataseek.iot.device.entity.DayLevel;
import com.dataseek.iot.device.mapper.DayLevelMapper;
import com.dataseek.iot.device.mapper.DeviceAttValueHisMapper;
import com.dataseek.iot.device.service.DayLevelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DayLevelServiceImpl extends ServiceImpl<DayLevelMapper, DayLevel> implements DayLevelService {

    @Autowired
    private DeviceAttValueHisMapper deviceAttValueHisMapper;

    @Override
    public void insertBatch(List<DayLevel> insertList) {
        this.saveBatch(insertList);
    }

    @Override
    public List<DayLevel> queryWeek(String jarCode, String deviceCode) {

        QueryWrapper<DayLevel> qw = new QueryWrapper<>();
        if (jarCode != null && !jarCode.isEmpty()) {
            qw.eq("jar_code", jarCode);
        }

        if (deviceCode != null && !deviceCode.isEmpty()) {
            qw.eq("device_code", deviceCode);
        }

        qw.ge("create_time", this.getZeroTime());
        qw.orderByAsc("create_time");
        return this.list(qw);
    }

    //获取每周周一的0点,譬如 2022-05-08 00:00:00
    private Date getZeroTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY); //以周一为首日
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return  calendar.getTime();
    }

    @Override
    public List<DayLevel> queryDay(String jarCode, String deviceCode) {
        return deviceAttValueHisMapper.query5CalValueForChange(jarCode, deviceCode);
    }

    @Override
    public List<DayLevel> queryDayForchange(Date fromDate, Date toDate, String jarCode, String deviceCode) {
        return deviceAttValueHisMapper.queryDayForchange(fromDate, toDate, jarCode, deviceCode);
    }

}
